package com.sudo.rpc.server.service.impl;

import com.sudo.rpc.server.service.ServerInfoService;
import com.sudo.rpc.server.utils.SysInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.SigarException;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ServerInfoServiceImpl implements ServerInfoService {

    @Override
    public Map<String, Object> getServerDynamicMemCpu() {
        try{
            Map<String, Object> objectMap = new HashMap<>();
            Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            Mem mem = SysInfoUtil.SIGAR.getMem();
            CpuPerc cpu = SysInfoUtil.SIGAR.getCpuPerc();
            objectMap.put("cpuTotal",String.format("%.2f",cpu.getCombined() * 100));//CpuPerc.format()
            objectMap.put("memUsedPercent",String.format("%.2f",mem.getUsedPercent()));
            objectMap.put("now", milliSecond);
            return objectMap;
        } catch (SigarException ex) {
            log.error("获取动态内存Cpu信息异常：",ex);
            throw new RuntimeException("获取动态内存Cpu信息异常", ex);
        }
    }


    @Override
    public Map<String, Object> getServerSysInfo() {
        Map<String, Object> objectMap = new HashMap<>();
        // ==== 服务器信息 ====
        SysInfoUtil.setServerInfo(objectMap);
        //==== Java信息 ====
        SysInfoUtil.setJavaInfo(objectMap);
        //==== CPU信息 ====
        SysInfoUtil.setCpuInfo(objectMap);
        //==== Mem信息 ====
        SysInfoUtil.setMemInfo(objectMap);
        //==== 硬盘信息 ====
        SysInfoUtil.setHardDiskInfo(objectMap);
        //==== 获取时间 ====
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = LocalDateTime.now().format(dtf);
        objectMap.put("update.time", format);
        return objectMap;
    }
}
